// src/contexts/AuthContext.tsx
import React, { createContext, useReducer } from 'react';
import axios from 'axios';

// 定义认证上下文的类型
interface AuthContextType {
  isLoggedIn: boolean; // 用户是否已登录
  login: (username: string, password: string) => Promise<void>; // 登录函数
  register: (username: string, password: string, email: string) => Promise<void>; // 注册函数
  logout: () => void; // 登出函数
}

// 定义状态类型
interface AuthState {
  isLoggedIn: boolean; // 登录状态
}

// 定义动作类型
type AuthAction = 
  | { type: 'LOGIN' }
  | { type: 'LOGOUT' };

// 创建认证上下文，初始值为 undefined
export const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 初始状态
const initialState: AuthState = {
  isLoggedIn: false,
};

// Reducer 函数处理认证状态
const authReducer = (state: AuthState, action: AuthAction): AuthState => {
  switch (action.type) {
    case 'LOGIN':
      return { ...state, isLoggedIn: true };
    case 'LOGOUT':
      return { ...state, isLoggedIn: false };
    default:
      return state;
  }
};

// 认证提供者组件
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState); // 使用 useReducer 管理状态

  // 处理 API 请求的通用函数
  const handleRequest = async (request: () => Promise<any>) => {
    try {
      return await request();
    } catch (error) {
      console.error('请求失败:', error); // 处理请求错误
      throw new Error('请求失败，请重试'); // 抛出通用错误
    }
  };

  // 登录逻辑
  const login = async (username: string, password: string) => {
    await handleRequest(async () => {
      const response = await axios.post('/api/login', { username, password });
      if (response.status === 200) {
        dispatch({ type: 'LOGIN' }); // 更新登录状态
      }
    });
  };

  // 注册逻辑
  const register = async (username: string, password: string, email: string) => {
    await handleRequest(async () => {
      const response = await axios.post('/api/register', { username, password, email });
      if (response.status === 201) {
        dispatch({ type: 'LOGIN' }); // 注册成功后自动登录
      }
    });
  };

  // 登出逻辑
  const logout = () => {
    dispatch({ type: 'LOGOUT' }); // 更新登录状态
  };

  return (
    // 提供认证上下文给子组件
    <AuthContext.Provider value={{ isLoggedIn: state.isLoggedIn, login, register, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
